package com.ftdc.app.thread;

import java.util.concurrent.Semaphore;

public class SemaphoreExampleController {
    public static void main(String[] args) {
        // 创建一个 Semaphore，最多允许 2 个线程同时访问
        Semaphore semaphore = new Semaphore(2);

        for (int i = 0; i < 5; i++) {
            new Thread(new Worker2(semaphore)).start();
        }
    }

}


class Worker2 implements Runnable {
    private final Semaphore semaphore;

    public Worker2(Semaphore semaphore) {
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            // 获取许可证
            semaphore.acquire();
            System.out.println(Thread.currentThread().getName() + " has acquired a permit.");

            // 模拟对共享资源的访问
            Thread.sleep((long) (Math.random() * 1000));

            System.out.println(Thread.currentThread().getName() + " is releasing a permit.");
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            // 释放许可证
            semaphore.release();
        }
    }
}
